﻿<%@ Page Title="Promotion Engine -  Document" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
    CodeBehind="DocLine.aspx.cs" Inherits="PromotionEngine.DocLine" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    <script type="text/javascript">
        var oCustomerPropertyLink = {};
        var oCustomer = {};
        var oItem = {};
        var oWarehouse = {};
        var oReferenceValue = {};
        var oSalesPerson = {};
        var oDocLine = {};
        var oDocHeader = {};
        var jsonCustomer;
        var oCustomerPropertyDetail = {};
        var isInsert = "1";
        var gird;
        var girdDetail;
        var propertyForDetailID = 0;
        var docEntry = 0;
        var isUpdate = false;
        var basePrice = 0;
        var selectItemID;
        var selectItemIndex = 0;
        var docDatePicker, docDueDatePicker;
        var record = 0;
        var docStatus = 1;
        var customerCombobox;
        var editRowIndex;
        var selectedCustomerID;
        function CreateNew() {
            $.ajax({
                type: "POST",
                url: "DocLine.aspx/ClearSessionData",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                },
                failure: function (response) {
                },
                error: function (response) {
                }
            });
            location.href = "DocLine.aspx?DocEntry=0&IsUpdate=false";
        }
        function OpenDocumentList() {
            var wnd = $("#documentList")
                        .kendoWindow({
                            title: "Document List",
                            modal: true,
                            visible: false,
                            resizable: false,
                            width: 1200,
                            height: 500,
                            content: { type: "POST", url: "DocHeader.aspx" },
                            iframe: true
                        }).data("kendoWindow");

            wnd.center().open();
        }
        function OpenPromotionDetail() {
            var wnd = $("#details")
                        .kendoWindow({
                            title: "Promotion Detail",
                            modal: true,
                            visible: false,
                            resizable: false,
                            width: 1100,
                            height: 500,
                            content: { type: "POST", url: "DocPromotion.aspx?DocEntry=" + docEntry + "&IsUpdate=false" },
                            iframe: true
                        }).data("kendoWindow");

            wnd.center().open();
        }
        function OpenPropertyLink() {
            var wnd = $("#link")
                        .kendoWindow({
                            title: "Doc Property Link",
                            modal: true,
                            visible: false,
                            resizable: false,
                            width: 705,
                            height: 550,
                            content: { type: "POST", url: "Doc-Property-Link.aspx?DocEntry=" + docEntry + "&DocStatus=" + docStatus + "", data: {} },
                            iframe: true
                        }).data("kendoWindow");

            wnd.center().open();
        }
        function OpenLineLink(e) {
            e.preventDefault();
            var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
            if (dataItem.LineStatus == '2') {
                var wnd = $("#propertyLink")
                        .kendoWindow({
                            title: "Doc Line Property Link",
                            modal: true,
                            visible: false,
                            resizable: false,
                            width: 705,
                            height: 550,
                            content: { type: "POST", url: "Doc-Line-Property-Link.aspx?LineNum=" + dataItem.LineNum + "&DocStatus=" + dataItem.DocStatus + "", data: { "DocLine": kendo.stringify(dataItem)} },
                            iframe: true
                        }).data("kendoWindow");

                //kendo.bind(wnd.element, dataItem);
                wnd.center().open();
            }
            else {
                
                setMasterMessage("You can not update. Please save this document before updating link.", "error");
            }
        }
        function closeDetail() {
            //parent.$("#details").data("kendoWindow").close();
            $.ajax({
                type: "POST",
                url: "DocLine.aspx/ClearSessionData",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                },
                failure: function (response) {
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }
        function LoadDocument(headerDocEntry, headerDocDate, headerDocDueDate,
                                headerRemarks, headerCustomerID, headerIsUpdate,
                                 headerDocStatus, headerReferenceName, headerCustomerName) {
            
            $.ajax({
                type: "POST",
                url: "DocLine.aspx/ClearSessionData",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    grid.dataSource.data([]);
                    $('#DocEntry').val(headerDocEntry);
                    var docDate = headerDocDate;
                    var docDateobj = kendo.parseDate(docDate);
                    var docDueDate = headerDocDueDate;
                    var docDueDateobj = kendo.parseDate(docDueDate);
                    $("#docDate").data("kendoDateTimePicker").value(null);
                    $("#docDueDate").data("kendoDatePicker").value(null);
                    $("#docDate").data("kendoDateTimePicker").value(docDateobj);
                    $("#docDueDate").data("kendoDatePicker").value(docDueDateobj);
                    $('#remarks').val(headerRemarks);
                    $("#cmbCustomers").val(headerCustomerName);
                    selectedCustomerID = headerCustomerID;
                    $('#lblDocStatus').text(headerReferenceName);
                    docEntry = headerDocEntry;
                    isUpdate = headerIsUpdate;
                    docStatus = headerDocStatus;
                    reLoadData();
                    DisplayDocStatus(docStatus)
                    $("#documentList").empty();
                    var url = "DocLine.aspx?DocEntry=" + docEntry + "&IsUpdate=true"
                    history.pushState({ docEntry: docEntry, IsUpdate: true }, "Document", url);
                },
                failure: function (response) {
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }
        function OpenItemList() {
            $("#itemList").empty();
            var wnd = $("#itemList")
                        .kendoWindow({
                            title: "List of Items",
                            modal: true,
                            visible: false,
                            resizable: false,
                            width: 1000,
                            height: 550,
                            content: { type: "POST", url: "ItemList.aspx", data: {} },
                            iframe: true
                        }).data("kendoWindow");

            wnd.center().open();
        }
        function OpenCustomerList() {
            $("#customerList").empty();
            var wnd = $("#customerList")
                        .kendoWindow({
                            title: "List of Customers",
                            modal: true,
                            visible: false,
                            resizable: false,
                            width: 1000,
                            height: 550,
                            content: { type: "POST", url: "CustomerList.aspx", data: {} },
                            iframe: true
                        }).data("kendoWindow");

            wnd.center().open();
        }
        function ChooseCustomer(customerID, customerName) {
            selectedCustomerID = customerID;
            $("#cmbCustomers").val(customerName)
            $("#customerList").data("kendoWindow").close();
        }
        function ChooseItem(itemID, itemCode, itemName, basePrice) {
            var rowData = $('#grid').data().kendoGrid.dataSource.data()[editRowIndex];
            rowData.set('ItemCode', itemCode);
            rowData.set('ItemName', itemName)
            rowData.set('ItemID', itemID);
            rowData.set('BasePrice', basePrice);
            if ($('#ItemID').data("kendoComboBox") != null) {
                $('#ItemID').data("kendoComboBox").value(itemID);
            }
            var lineTotal = 0;
            lineTotal = rowData.BasePrice * rowData.Quantity;
            var totalAfterDiscount = lineTotal - rowData.DiscountAmount
            rowData.set('TotalAfterDiscount', totalAfterDiscount);
            rowData.set('LineTotal', lineTotal);
            UpdateSubTotal();
            $("#itemList").data("kendoWindow").close();
        }
        // back/forward hit
        //        window.addEventListener("popstate", function (e) {
        //            location.href = document.location;
        //        });
        window.addEventListener('load', function () {
            setTimeout(function () {
                window.addEventListener('popstate', function () {
                    location.href = document.location;
                });
            }, 0);
        });

        function itemkendoComboBox(container, options) {
            $('<input disabled  style="width:85%;"  required validationMessage="Pls select item." data-text-field="ItemName" data-value-field="ItemID" Name="ItemID" ID="ItemID" data-bind="value:' + options.field + '"/>')
                        .appendTo(container)
                        .kendoComboBox({
                            autoBind: false,
                            filter: "contains",
                            placeholder: "[Select Item]",
                            suggest: true,
                            dataSource: oItem,
                            change: onChange,
                            select: onSelect

                        });
            $('<span class="k-icon k-i-search" style="margin-left:8px;width:16px;" onclick="OpenItemList()" title="Choose item" ></span>').appendTo(container);
            $('<span class="k-invalid-msg" data-for="ItemID"></span>').appendTo(container);

        }

        function warehousekendoComboBox(container, options) {
            $('<input required  validationMessage="Pls select warehouse." data-text-field="WarehouseName" data-value-field="WarehouseID" Name="WarehouseID" ID="WarehouseID" data-bind="value:' + options.field + '"/>')
                        .appendTo(container)
                        .kendoComboBox({
                            autoBind: false,
                            filter: "contains",
                            placeholder: "[Select Warehouse]",
                            suggest: true,
                            dataSource: oWarehouse,
                            change: function (e) {
                                var cmb = this;
                                if (cmb.selectedIndex < 0) {
                                    cmb.value(null);
                                }
                            }
                        });
            $('<span class="k-invalid-msg" data-for="WarehouseID"></span>').appendTo(container);
        }
        function itemTypeComboBox(container, options) {
            $('<input disabled  data-text-field="ReferenceName" data-value-field="ReferenceValue" Name="ItemType" ID="ItemType" data-bind="value:' + options.field + '"/>')
                        .appendTo(container)
                        .kendoComboBox({
                            autoBind: false,
                            filter: "contains",
                            placeholder: "[Select Item Type]",
                            suggest: true,
                            dataSource: oReferenceValue
                        });
        }
        function salesPersonkendoComboBox(container, options) {
            $('<input required  validationMessage="Pls select sales person." data-text-field="SalesPersonName" data-value-field="SalesPersonID" Name="SalesPersonID" ID="SalesPersonID" data-bind="value:' + options.field + '"/>')
                        .appendTo(container)
                        .kendoComboBox({
                            autoBind: false,
                            filter: "contains",
                            placeholder: "[Select Sales Person]",
                            suggest: true,
                            dataSource: oSalesPerson,
                            change: function (e) {
                                var cmb = this;
                                if (cmb.selectedIndex < 0) {
                                    cmb.value(null);
                                }
                            }
                        });
            $('<span class="k-invalid-msg" data-for="SalesPersonID"></span>').appendTo(container);
        }
        function itemTextBox(container, options) {
            //$('<span class="k-textbox k-space-right"><input style="width:100%;" name="ItemCode" class="k-input k-textbox" type="text" data-bind="value:' + options.field + '"/><a href="#" onclick="OpenItemList()" class="k-icon k-i-search">&nbsp;</a></span>').appendTo(container);
            $('<input style="width:80%;" name="ItemCode" class="k-input k-textbox" type="text" data-bind="value:' + options.field + '"/>').appendTo(container);
            $('<span class="k-icon k-i-search" style="margin-left:8px;width:16px;" onclick="OpenItemList()"  title="Choose item" ></span>').appendTo(container);
        }
        function discountAmtTextBox(container, options) {
            $('<input name="DiscountAmount" class="k-input k-textbox" type="text" data-bind="value:' + options.field + '"/>').appendTo(container);
        }
        function totalAfterDiscountTextBox(container, options) {
            $('<input name="TotalAfterDiscount" class="k-input k-textbox" type="text" data-bind="value:' + options.field + '"/>').appendTo(container);
        }
        function onChange() {
            var cmb = this;
            if (cmb.selectedIndex < 0) {
                cmb.value(null);
            }
            else {
                var changedItemID = this.value();
                var itemCode;
                $.each(oItem, function (i, o) {
                    if (o.BasePrice) {
                        if (o.ItemID == changedItemID) {
                            basePrice = parseFloat(o.BasePrice);
                            itemCode = o.ItemCode;
                        }
                    }
                });

                var items = $("#grid").data("kendoGrid").dataSource.data();
                for (i = 0; i < items.length; i++) {
                    var item = items[i];
                    if (item.ItemID == changedItemID) {
                        item.set('BasePrice', basePrice)
                        item.set('ItemCode', itemCode)
                        var lineTotal = basePrice * item.Quantity;
                        var totalAfterDiscount = lineTotal - rowData.DiscountAmount
                        item.set('TotalAfterDiscount', totalAfterDiscount);
                        item.set('LineTotal', lineTotal);
                        UpdateSubTotal();
                        break;
                    }
                }
            }
        }
        function onSelect(e) {
            basePrice = 0;
            selectItemID = "";
            //selectItemIndex = e.item.index();

            var dataItem = this.dataItem(e.item.index());

            $.each(oItem, function (i, o) {
                if (o.BasePrice) {
                    if (o.ItemID == dataItem.ItemID) {
                        basePrice = parseFloat(o.BasePrice);

                    }
                }
            });
            selectItemID = dataItem.ItemID;
        }
        //Get All Item
        function GetItems() {
            $.ajax({
                type: "POST",
                url: "DocLine.aspx/GetItems",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    oItem.BasePrice = 0.0;
                    oItem = $.parseJSON(response.d);
                    $.each(oItem, function (i, o) {
                        if (o.BasePrice) {
                            var price = parseFloat(o.BasePrice);
                            oItem[i].BasePrice = price;
                        }
                    });
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }
        function GetWarehouses() {
            $.ajax({
                type: "POST",
                url: "WareHouse.aspx/GetWareHouses",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    oWarehouse = $.parseJSON(response.d);
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }
        function GetSalesPerson() {
            $.ajax({
                type: "GET",
                url: "SalesPerson.aspx/GetSalesPersonForManager",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    oSalesPerson = $.parseJSON(response.d);
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }
        function GetReference() {
            $.ajax({
                type: "GET",
                url: "DocLine.aspx/GetAllReferenceValueItemType",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    oReferenceValue = $.parseJSON(response.d);
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }
        function readonlyEditor(container, options) {
            grid.closeCell();
        }
        var selectedRow;
        $(document).ready(function () {
            //Load Item
            GetItems();
            GetWarehouses();
            GetSalesPerson();
            GetReference();
            isUpdate = '<%= Request.QueryString["IsUpdate"] %>';
            $('#DocEntry').val('<%= Request.QueryString["DocEntry"] %>');
            //Load Customer
            docEntry = $('#DocEntry').val();

            if (docEntry == '0') {
                $('#btnPropertyLink').attr('disabled', 'disabled');
                $('#btnPropertyLink').addClass("k-button k-state-disabled");

                $('#btnPromotionDetail').attr('disabled', 'disabled');
                $('#btnPromotionDetail').addClass("k-button k-state-disabled");

                $('#btnCloseDoc').attr('disabled', 'disabled');
                $('#btnCloseDoc').addClass("k-button k-state-disabled");
            }
            else {
                GetHeaderByDocEntry();
                $('#btnPropertyLink').removeAttr('disabled');
                $('#btnPropertyLink').removeClass("k-state-disabled");

                $('#btnPromotionDetail').removeAttr('disabled');
                $('#btnPromotionDetail').removeClass("k-state-disabled");

            }
            var viewModel = kendo.observable({
                allowCustomValues: false,
                customerData: new kendo.data.DataSource({
                    transport: {
                        read: {
                            type: "GET",
                            url: "Customer.aspx/GetODataCustomers",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json"
                        },

                        serverPaging: true,
                        serverSorting: true,
                        serverFiltering: true
                    },

                    type: "odata", //Important!!!!
                    schema: {
                        data: function (a) {
                            if (a.d != null) {
                                var data = a.d;
                                return data;
                            }
                        },
                        allowCustomValues: false,
                        model: {
                            id: "CustomerID",
                            fields: {
                                CustomerID: { type: "string", validation: { required: true} },
                                CustomerName: { type: "string", validation: { required: true} }
                            }
                        }
                    }
                })
            });
            //customerCombobox.dataSource.read();
            // create DateTimePicker from input HTML element
            docDatePicker = $("#docDate").kendoDateTimePicker({
                value: new Date(),
                required: true
            }).data("kendoDateTimePicker");
            // create DateTimePicker from input HTML element
            docDueDatePicker = $("#docDueDate").kendoDatePicker({
                value: new Date(),
                required: true
            }).data("kendoDatePicker");
            if (isUpdate == 'true') {
                var docDate = '<%= Request.QueryString["DocDate"] %>';
                var docDateobj = kendo.parseDate(docDate);
                var docDueDate = '<%= Request.QueryString["DocDueDate"] %>';
                var docDueDateobj = kendo.parseDate(docDueDate);
                docDatePicker.value(docDateobj);
                docDueDatePicker.value(docDueDateobj);
                $('#remarks').val('<%= Request.QueryString["Remark"] %>');
                $("#cmbCustomers").val('<%= Request.QueryString["CustomerID"] %>');
            }
            //Clear Session

            $.ajax({
                type: "POST",
                url: "DocLine.aspx/ClearSessionData",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    //Load Grid
                    grid = $("#grid").kendoGrid({
                        dataSource: {
                            transport: {
                                read: {
                                    type: "GET",
                                    url: "DocLine.aspx/GetDocLines",
                                    data: '',
                                    contentType: "application/json; charset=utf-8",
                                    dataType: "json",
                                    complete: function (jqXHR, textStatus) { UpdateSubTotal(); }
                                },
                                destroy: {
                                    type: "GET",
                                    url: "DocLine.aspx/DeleteDocLine",
                                    contentType: "application/json; charset=utf-8",
                                    dataType: "json"
                                },
                                create: {
                            },
                            parameterMap: function (data, operation) {
                                if (operation === "read") {
                                    return { docEntry: docEntry };
                                }
                                if (operation === "destroy") {
                                    return { lineNum: data.LineNum };
                                }
                            },
                            serverPaging: true,
                            serverSorting: true,
                            serverFiltering: true
                        },
                        type: "odata", //Important!!!!
                        schema: {
                            data: function (a) {
                                if (a.d != null) {
                                    var data = a.d.Data;
                                    return data;
                                }
                            },
                            total: "d.Count",
                            model: {
                                id: "LineNum",
                                fields: {
                                    DocEntry: { type: "string" },
                                    LineNum: { type: "string" },
                                    ItemID: { type: "string", validation: {
                                        required: { message: "Product Name is required" }
                                    }
                                    },
                                    ItemCode: { type: "string" },
                                    ItemName: { type: "string" },
                                    WarehouseID: { type: "string" },
                                    WarehouseName: { type: "string" },
                                    SalesPersonID: { type: "string" },
                                    SalesPersonName: { type: "string" },
                                    ItemType: { type: "string" },
                                    ReferenceName: { type: "string" },
                                    Quantity: { type: "number" },
                                    BasePrice: { type: "number" },
                                    DiscountAmount: { type: "number" },
                                    LineTotal: { type: "number" },
                                    LineStatus: { type: "LineStatus" },
                                    DocStatus: { type: "LineStatus" },
                                    TotalAfterDiscount: { type: "number" }
                                }
                            }
                        }
                    },
                    sortable: true,
                    resizable: true,
                    height: 300,
                    selectable: "row",
                    toolbar: [{ name: 'create', text: 'Add New Item' }, { name: 'excel'}],
                    excel: {
                        fileName: "Document Line.xlsx",
                        filterable: true
                    },
                    batch: true,
                    columns: [
                            { field: "DocEntry", title: "DocEntry", width: 100, hidden: true },
                            { field: "LineNum", title: "LineNum", width: 150, hidden: true },
                            { field: "LineStatus", title: "LineNum", width: 150, hidden: true },
                            { field: "ItemCode", title: "Item Code", width: 180, editor: itemTextBox, template: "#=ItemCode#" },
                            { field: "ItemID", title: "Item Name", width: 250, editor: itemkendoComboBox, template: "#=ItemName#" },
                            { field: "ItemName", title: "Item Name", width: 20, hidden: true },
                            { field: "ItemType", title: "Item Type", width: 200, editor: itemTypeComboBox, template: "#=ReferenceName#" },
                            { field: "WarehouseID", title: "Warehouse", width: 200, editor: warehousekendoComboBox, template: "#=WarehouseName#" },
                            { field: "SalesPersonID", title: "Sales Person", width: 200, editor: salesPersonkendoComboBox, template: "#=SalesPersonName#" },
                            { field: "Quantity", title: "Quantity", width: 120, attributes: { style: "text-align:right;"} },
                            { field: "BasePrice", title: "Base Price", width: 150, format: "{0:n}", type: "number", attributes: { style: "text-align:right;"} },
                            { field: "DiscountAmount", title: "Discount Amount", width: 150, format: "{0:n}", type: "number", attributes: { style: "text-align:right;" }, editor: discountAmtTextBox },
                            { field: "LineTotal", title: "Line Total", width: 180, format: "{0:n}", type: "number", attributes: { style: "text-align:right;"} },
                            { field: "TotalAfterDiscount", title: "Total After Discount", width: 200, format: "{0:n}", type: "number", attributes: { style: "text-align:right;" }, editor: totalAfterDiscountTextBox },
                            { command: ["edit", "destroy", { text: "Link", click: OpenLineLink}], title: "Action", width: "270px" }
                            ],
                    editable: {
                        mode: "inline",
                        confirmation: "Are you sure you want to remove this item?",
                        createAt: "bottom"
                    },
                    edit: function (e) {
                        $('[name="DocEntry"]').attr("disabled", true);
                        $('[name="LineNum"]').attr("disabled", true);
                        $('[name="LineTotal"]').attr("disabled", true);
                        $('[name="TotalAfterDiscount"]').attr("disabled", true);
                        $('[name="DiscountAmount"]').attr("disabled", true);
                        if(e.container.find("input").attr("name") == "DiscountAmount") { 
                            this.closeCell();
                              }
                        if (e.model.isNew()) {
                            $("a.k-grid-update")[0].innerHTML = "<span class='k-icon k-update'></span>Save";
                            isInsert = "1";
                            e.container
                     .find("input[name=DocEntry]") // get the input element for the field
                     .val($("#DocEntry").val()) // set the value
                     .change(); // trigger change in order to notify the model binding
                            e.model.set("Quantity", 1);
                            e.model.set("DiscountAmount", 0);
                            e.model.set("ItemType", '1');
                            $('#ItemType').data("kendoComboBox").value('1');
                        }
                        else {

                            isInsert = "2";
                        }
                    },
                    save: function (e) {
                        var listTextBox = $("input:text");
                        for (var i = 0; i < listTextBox.length; i++) {
                            var name = listTextBox[i].name;
                            if (name.length > 0) {
                                oDocLine[name] = $("[name=" + name + "]").val();
                            }
                        }
                        oDocLine.ItemID = $('#ItemID').data("kendoComboBox").value();
                        oDocLine.ItemName = $('#ItemID').data("kendoComboBox").text();

                        oDocLine.WarehouseID = $('#WarehouseID').data("kendoComboBox").value();
                        oDocLine.WarehouseName = $('#WarehouseID').data("kendoComboBox").text();

                        oDocLine.SalesPersonID = $('#SalesPersonID').data("kendoComboBox").value();
                        oDocLine.SalesPersonName = $('#SalesPersonID').data("kendoComboBox").text();
                        oDocLine.ItemType = $('#ItemType').data("kendoComboBox").value();
                        oDocLine.ReferenceName = $('#ItemType').data("kendoComboBox").text();
                        //Update or Insert Item
                        $.ajax({
                            type: "POST",
                            url: "DocLine.aspx/UpdateDoc",
                            data: JSON.stringify({
                                oDocLine: JSON.stringify(oDocLine),
                                isInsert: isInsert,
                                rowIndex: 1
                            }),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (data) {
                                grid.dataSource.read();
                            },
                            error: function (xhr, status, err) {
                                var err = eval("(" + xhr.responseText + ")");
                                alert(err.Message);
                            }
                        });
                    },
                    dataBound: onDataBound//,
                    //                    dataBinding: function () {
                    //                       
                    //                    }
                }).data("kendoGrid");
            },
            failure: function (response) {
            },
            error: function (response) {
            }
        });
    });

    function onDataBound(e) {
        //record = (this.dataSource.page() - 1) * this.dataSource.pageSize();
        var grid = $("#grid").data("kendoGrid");

        $(grid.tbody).on("click", "td", function (e) {
            var row = $(this).closest("tr");
            editRowIndex = $("tr", grid.tbody).index(row);
            var colIdx = $("td", row).index(this);
            //alert(editRowIndex + '-' + colIdx);
        });

        var docStatusOfLine;

        //Selects all edit buttons
        $("#grid tbody tr .k-grid-edit").each(function () {
            var currentDataItem = $("#grid").data("kendoGrid").dataItem($(this).closest("tr"));
            //Check in the current dataItem if the row is editable
            docStatusOfLine = currentDataItem.DocStatus;
            if (currentDataItem.DocStatus == 2) {
                $(this).remove();
            }
        });

        //Selects all delete buttons
        $("#grid tbody tr .k-grid-delete").each(function () {

            var currentDataItem = $("#grid").data("kendoGrid").dataItem($(this).closest("tr"));
            //Check in the current dataItem if the row is deletable
            if (currentDataItem.DocStatus == 2) {
                $(this).remove();
            }
        });
        if (docStatusOfLine == 2) {
            $("#grid .k-add").parent().hide();
        }
        else {
            $("#grid .k-add").parent().show();
        }
        $(grid.tbody).on("blur", "td", function (e) {
            var row = $(this).closest("tr");
            var rowIdx = $("tr", grid.tbody).index(row);
            var colIdx = $("td", row).index(this);
            var colName = $('#grid').find('th').eq(colIdx).text();
            var columnField = $('#grid').find("th").eq(colIdx).attr("data-field");
            var rowData = $('#grid').data().kendoGrid.dataSource.data()[rowIdx];
            if (columnField == 'Quantity' || columnField == 'BasePrice' || columnField == 'DiscountAmount') {
                var discountAmt = 0;
                var priceAfterDiscount = 0;
                var totalAfterDiscount = 0;
                var lineTotal = 0, totalAfterDiscount = 0;
                lineTotal = rowData.BasePrice * rowData.Quantity;
                totalAfterDiscount = lineTotal - rowData.DiscountAmount
                rowData.set('LineTotal', lineTotal);
                rowData.set('TotalAfterDiscount', totalAfterDiscount);
                UpdateSubTotal();
            }
            else if (columnField == 'ItemCode') {
                var itemID, basePrice, itemName;
                $.each(oItem, function (i, o) {
                    if (o.BasePrice) {
                        if (o.ItemCode == rowData.ItemCode) {
                            basePrice = parseFloat(o.BasePrice);
                            itemID = o.ItemID;
                            itemName = o.ItemName
                        }
                    }
                });

                var items = $("#grid").data("kendoGrid").dataSource.data();
                for (i = 0; i < items.length; i++) {
                    var item = items[i];
                    if (item.ItemCode == rowData.ItemCode) {
                        item.set('BasePrice', basePrice);
                        item.set('ItemID', itemID);
                        if ($('#ItemID').data("kendoComboBox") != null) {
                            $('#ItemID').data("kendoComboBox").value(itemID);
                        }
                        item.set('ItemName', itemName)
                        var lineTotal = basePrice * item.Quantity;
                        var totalAfterDiscount = lineTotal - rowData.DiscountAmount
                        item.set('LineTotal', lineTotal);
                        item.set('TotalAfterDiscount', totalAfterDiscount);
                        UpdateSubTotal();
                        break;
                    }
                }
            }
        });

    }
    function UpdateSubTotal() {
        var items = $("#grid").data("kendoGrid").dataSource.data();
        var subTotal = 0;
        for (i = 0; i < items.length; i++) {
            var item = items[i];
            //subTotal += item.LineTotal
            subTotal += item.TotalAfterDiscount
        }
        var totalMoney = format2(subTotal, "");
        $('#subtotal').text(totalMoney);
    }
    function UpdateProcess() {
        
        var validator = $("#aspnetForm").kendoValidator().data("kendoValidator");
        if (validator.validate()) {
            oDocHeader.DocEntry = $("#DocEntry").val();
            oDocHeader.CustomerID = selectedCustomerID;
            oDocHeader.CustomerName = $('#cmbCustomers').val()
            oDocHeader.DocDate = $("#docDate").val();
            oDocHeader.DocTime = $("#docDate").val()
            oDocHeader.DocDueDate = $("#docDueDate").val();
            oDocHeader.Remark = $("#remarks").val();
            oDocHeader.SubTotal = Number($("#subtotal").text().replace(/[^0-9\.]+/g, ""));
            oDocHeader.DocStatus = docStatus;
            if (oDocHeader.CustomerName == '') {
                
                setMasterMessage("Please select customer.", "error");
                return;
            }
            if (oDocHeader.DocDate == '') {
                
                setMasterMessage("Please select Doc Date.", "error");
                return;
            }
            if (oDocHeader.DocDueDate == '') {
                
                setMasterMessage("Please select Doc Due Date.", "error");
                return;
            }
            $.ajax({
                type: "POST",
                url: "DocLine.aspx/UpdateDocToDB",
                data: JSON.stringify({
                    oDocHeader: JSON.stringify(oDocHeader),
                    isUpdate: isUpdate
                }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    if (data.d != "0") {
                        if ($.isNumeric(data.d)) {
                            isUpdate = 'true';
                            $('#DocEntry').val(data.d);
                            //Load Customer
                            docEntry = $('#DocEntry').val();
                            grid.dataSource.data([]);
                            $.ajax({
                                type: "POST",
                                url: "DocLine.aspx/ClearSessionData",
                                data: '',
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                success: function (response) {
                                    var url = "DocLine.aspx?DocEntry=" + docEntry + "&IsUpdate=true"
                                    history.pushState({ docEntry: docEntry, IsUpdate: true }, "Document", url);
                                    reLoadData();
                                },
                                failure: function (response) {
                                },
                                error: function (jqXHR, textStatus, errorThrown) {
                                    if (jqXHR.status == 500) {
                                        alert('Internal error: ' + jqXHR.responseText);
                                    } else {
                                        alert('Unexpected error.' + jqXHR.responseText);
                                    }
                                }
                            });
                            
                            setMasterMessage("Operation complete successful!", "success");
                            
                        }
                        else {
                            
                            setMasterMessage(data.d, "error");
                        }
                    }
                    else {
                        
                        setMasterMessage(data.d, "error");
                    }
                }
            ,
                error: function (xhr, status, err) {
                    var err = eval("(" + xhr.responseText + ")");
                    alert(err.Message);
                }
            });

        } else {
        }
    }
    function ClosedDoc() {
        
        var r = confirm("Do you really want to close this document?");
        if (r == true) {
            var docEntry = $("#DocEntry").val();
            $.ajax({
                type: "POST",
                url: "DocLine.aspx/ClosedDoc",
                data: JSON.stringify({
                    docEntry: docEntry
                }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    if (data.d != "0") {
                        if ($.isNumeric(data.d)) {
                            docStatus = 2;
                            grid.dataSource.data([]);
                            grid.dataSource.read();
                            $("#lblDocStatus").text("Closed");
                            
                            setMasterMessage("Operation complete successful!", "success");
                            DisplayDocStatus("2");
                        }
                        else {
                            
                            setMasterMessage(data.d, "error");
                        }
                    }
                    else {
                        
                        setMasterMessage(data.d, "error");
                    }
                }
            ,
                error: function (xhr, status, err) {
                    var err = eval("(" + xhr.responseText + ")");
                    alert(err.Message);
                }
            });
        } else {

        }
    }
    function reLoadData() {
        grid.dataSource.read();
        if (docEntry != '0') {
            $('#btnPropertyLink').removeAttr('disabled');
            $('#btnPropertyLink').removeClass("k-state-disabled");

            $('#btnPromotionDetail').removeAttr('disabled');
            $('#btnPromotionDetail').removeClass("k-state-disabled");
            if (docStatus != "2") {
                $('#btnCloseDoc').removeAttr('disabled');
                $('#btnCloseDoc').removeClass("k-state-disabled");
            }
        }
    }
    function DisplayDocStatus(docStatus) {
        if (docStatus == "2") {
            $('#btnSave').attr('disabled', 'disabled');
            $('#btnSave').addClass("k-button k-state-disabled");
            $('#btnCloseDoc').attr('disabled', 'disabled');
            $('#btnCloseDoc').addClass("k-button k-state-disabled");
            docDatePicker.enable(false);
            docDueDatePicker.enable(false);
            $('#spanChooseCustomer').hide();
        }
        else {
            $('#btnSave').removeAttr('disabled');
            $('#btnSave').removeClass("k-state-disabled");
            $('#btnCloseDoc').removeAttr('disabled');
            $('#btnCloseDoc').removeClass("k-state-disabled");
            docDatePicker.enable();
            docDueDatePicker.enable();
            $('#spanChooseCustomer').show();
        }
    }
    function GetHeaderByDocEntry() {
        $.ajax({
            type: "POST",
            url: "DocLine.aspx/GetDocHeaderByDocEntry",
            data: JSON.stringify({
                docEntry: docEntry
            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                var result = JSON.parse(response.d);
                if (result.Table) {
                    var docHeader = result.Table;
                    if (docHeader.length > 0) {
                        docHeader = docHeader[0];
                        docEntry = docHeader.DocEntry;

                        $('#DocEntry').val(docEntry);
                        var docDate = docHeader.DocDate;
                        var docDateobj = kendo.parseDate(docDate);
                        var docDueDate = docHeader.DocDueDate;
                        var docDueDateobj = kendo.parseDate(docDueDate);
                        $("#docDate").data("kendoDateTimePicker").value(null);
                        $("#docDueDate").data("kendoDatePicker").value(null);
                        $("#docDate").data("kendoDateTimePicker").value(docDateobj);
                        $("#docDueDate").data("kendoDatePicker").value(docDueDateobj);
                        $('#remarks').val(docHeader.Remark);
                        if (docHeader.ReferenceName != null) {
                            $('#lblDocStatus').text(docHeader.ReferenceName);
                            docStatus = docHeader.DocStatus;
                        }
                        else {
                            $('#lblDocStatus').text("Draft");
                            docStatus = "1";
                        }
                        $("#cmbCustomers").val(docHeader.CustomerName);
                        selectedCustomerID = docHeader.CustomerID;
                        DisplayDocStatus(docStatus);
                        isUpdate = true;
                    }
                }
            },
            failure: function (response) {
                alert(response.d);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                if (jqXHR.status == 500) {
                    alert('Internal error: ' + jqXHR.responseText);
                } else {
                    alert('Unexpected error.' + jqXHR.responseText);
                }
            }
        });
    }
    function GetLastRecord() {
        $.ajax({
            type: "POST",
            url: "DocLine.aspx/GetLastRecord",
            data: '',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {

                var result = JSON.parse(response.d);
                if (result.Table) {
                    var docHeader = result.Table;
                    if (docHeader.length > 0) {
                        docHeader = docHeader[0];
                        grid.dataSource.data([]);
                        docEntry = docHeader.DocEntry;
                        docStatus = docHeader.DocStatus;
                        $('#DocEntry').val(docEntry);
                        var docDate = docHeader.DocDate;
                        var docDateobj = kendo.parseDate(docDate);
                        var docDueDate = docHeader.DocDueDate;
                        var docDueDateobj = kendo.parseDate(docDueDate);
                        $("#docDate").data("kendoDateTimePicker").value(null);
                        $("#docDueDate").data("kendoDatePicker").value(null);
                        $("#docDate").data("kendoDateTimePicker").value(docDateobj);
                        $("#docDueDate").data("kendoDatePicker").value(docDueDateobj);
                        $("#remarks").val(docHeader.Remark);
                        if (docHeader.ReferenceName != null) {
                            $('#lblDocStatus').text(docHeader.ReferenceName);
                            docStatus = docHeader.DocStatus;
                        }
                        else {
                            $('#lblDocStatus').text("Draft");
                            docStatus = "1";
                        }
                        $("#cmbCustomers").val(docHeader.CustomerName);
                        selectedCustomerID = docHeader.CustomerID;
                        DisplayDocStatus(docStatus);
                        isUpdate = true;
                        $.ajax({
                            type: "POST",
                            url: "DocLine.aspx/ClearSessionData",
                            data: '',
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (response) {
                                reLoadData();
                                var url = "DocLine.aspx?DocEntry=" + docEntry + "&IsUpdate=true"
                                history.pushState({ docEntry: docEntry, IsUpdate: true }, "Document", url);

                            },
                            failure: function (response) {
                            },
                            error: function (jqXHR, textStatus, errorThrown) {
                                if (jqXHR.status == 500) {
                                    alert('Internal error: ' + jqXHR.responseText);
                                } else {
                                    alert('Unexpected error.' + jqXHR.responseText);
                                }
                            }
                        });
                    }
                }
            },
            failure: function (response) {
                alert(response.d);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                if (jqXHR.status == 500) {
                    alert('Internal error: ' + jqXHR.responseText);
                } else {
                    alert('Unexpected error.' + jqXHR.responseText);
                }
            }
        });
    }
    function calcAvg() {
        if (grid == null) return;

        var ds = grid.dataSource;
        if (ds == null) return;

        var data = ds.data();
        if (data == null) return;

        var target = $('#val');
        var vSum = 0.0;
        if (data && target) {
            for (var i = 0; i < data.length; i++) {
            }

        }
    }

    </script>
    <table style="width: 100%;">
        <tr>
            <td>
                <label for="DocEntry">
                    DocEntry</label>
            </td>
            <td>
                <input name="DocEntry" id="DocEntry" class="k-input k-textbox" type="text" readonly="readonly"
                    style="width: 300px;" />
            </td>
            <td>
                Doc Date / Time
            </td>
            <td>
                <input id="docDate" />
            </td>
            <td>
                Doc Status
            </td>
            <td>
                <span id="lblDocStatus" style="font-weight: 700; color: #0000FF">Draft</span>
            </td>
        </tr>
        <tr>
            <td>
                <label for="Company">
                    Customer</label>
            </td>
            <td>
                <input type="text" id="cmbCustomers" name="cmbCustomers" class="k-textbox" placeholder="Select customer"
                    required validationmessage="Please select customer." style="width: 300px;" disabled />
                <span class="k-icon k-i-search" style="margin-left: 0px; width: 16px; cursor: pointer;"
                    onclick="OpenCustomerList()" title="Choose Customer" id="spanChooseCustomer">
                </span><span class="k-invalid-msg" data-for="cmbCustomers"></span><span class="fake">
                    * </span>
                <br />
            </td>
            <td>
                Doc Due Date
            </td>
            <td>
                <input id="docDueDate" style="width: 210px;" />
            </td>
            <td>
                &nbsp;
            </td>
            <td>
                &nbsp;
            </td>
        </tr>
    </table>
    <hr />
    <div id="customerList">
    </div>
    <div id="itemList">
    </div>
    <div id="documentList">
    </div>
    <div id="propertyLink">
    </div>
    <div id="link">
    </div>
    <div id="details">
    </div>
    <div id="grid">
    </div>
    <table style="width: 100%;" border="0">
        <tr>
            <td style="width: 10%;">
                Remarks:
            </td>
            <td valign="middle" style="width: 30%;">
                <textarea id="remarks" cols="80" rows="2" class="k-textbox" style="width: 80%;"></textarea>
            </td>
            <td style="width: 30%;">
            </td>
            <td align="right" style="width: 20%;">
                <label for="SubTotal">
                    Sub Total:</label>
            </td>
            <td align="right" style="width: 10%;">
                <label id="subtotal">
                    0</label>
            </td>
        </tr>
    </table>
    <hr />
    <table style="width: 100%;" border="0">
        <tr>
            <td align="left" style="width: 70%">
                <div class="k-edit-buttons k-state-default">
                    <button type="button" id="btnSave" onclick="UpdateProcess();" class="k-button k-button-icontext k-primary"
                        style="width: 80px;">
                        <span class="k-icon k-update"></span>Save</button>
                    <button type="button" id="btnCreateNew" onclick="CreateNew();" class="k-button k-button-icontext k-primary"
                        style="width: 120px;">
                        <span class="k-icon k-i-plus"></span>Create New</button>
                    <button type="button" id="btnCloseDoc" onclick="ClosedDoc();" class="k-button k-button-icontext k-primary"
                        style="width: 120px;">
                        <span class="k-icon k-i-close"></span>Close Doc.</button>
                    <button type="button" id="btnPropertyLink" onclick="OpenPropertyLink()" class="k-button k-button-icontext k-primary"
                        style="width: 160px;">
                        <span class="k-icon k-i-hbars"></span>Property Link</button>
                    <button type="button" id="btnPromotionDetail" onclick="OpenPromotionDetail()" class="k-button k-button-icontext k-primary"
                        style="width: 160px;">
                        <span class="k-icon k-i-hbars"></span>Promotion Detail</button>
                    <button type="button" id="btnDocumentList" onclick="OpenDocumentList()" class="k-button k-button-icontext k-primary"
                        style="width: 130px;">
                        <span class="k-icon k-i-hbars"></span>Document List</button>
                    <button type="button" id="btnLastRecord" onclick="GetLastRecord()" class="k-button k-button-icontext k-primary"
                        style="width: 130px;">
                        <span class="k-icon k-i-seek-e"></span>Last Record</button>
                </div>
            </td>
            <td>
            </td>
        </tr>
    </table>
</asp:Content>
